//
//  ContentViewController.m
//  iGSS
//
//  Copyright 2010 Electronic Business Systems Ltd.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//

#import "ContentViewController.h"

#import "NoticeViewController.h"

#import "NSString+GSSAdditions.h"
#import "FormattingUtilities.h"
#import "GSSCommunicator.h"

#define ASK_SIZE_THRESHOLD 5000000LL

@implementation ContentViewController

@synthesize file;
@synthesize folder;

@synthesize versionLabel;
@synthesize versionPreviousButton;
@synthesize versionNextButton;

- (void)downloadData {
    if (self.file.size > ASK_SIZE_THRESHOLD) {
        NSString *message = [NSString stringWithFormat:LocalizedString(@"{Are you sure?}"),
                             [FormattingUtilities byteStringForSize:self.file.size]];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:LocalizedString(@"File too large")
                                                            message:message
                                                           delegate:self
                                                  cancelButtonTitle:LocalizedString(@"Cancel")
                                                  otherButtonTitles:LocalizedString(@"Download"), nil];
        [alertView show];        
    } else {
        [[GSSCommunicator defaultCommunicator] updateFileObject:self.file];
        if (!loaded)
            self.activityView.hidden = NO;
    }
}

//MARK: Instance methods
//MARK: -

- (id)initWithFile:(GSSObject *)aFile inFolder:(GSSObject *)aFolder {
    // To be overriden by subclasses
    return nil;
}

- (void)dealloc {
    [file release];
    [folder release];
    
    [activityViewController release];
    [errorViewController release];
    
    [toolbar release];
    [versionLabel release];
    [versionPreviousButton release];
    [versionNextButton release];
    
    [super dealloc];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)anObject change:(NSDictionary *)change context:(void *)context {
    self.activityView.hidden = YES;
    self.errorView.hidden = YES;
    
    if ([keyPath isEqualToString:@"meta"]) {
        [self reloadMeta];
    } else if ([keyPath isEqualToString:@"data"]) {
        [self reloadData];
        loaded = YES;
    } else if ([keyPath isEqualToString:@"error"]) {
        self.errorView.hidden = NO;
    }
}


//MARK: -
//MARK: Properties

- (UIView *)activityView {
    if (!activityViewController) {
        activityViewController = [[NoticeViewController alloc] initWithNibName:@"ActivityView" bundle:nil];
        activityViewController.message = LocalizedString(@"Loading...");
        [self.view addSubview:activityViewController.view];
        activityViewController.view.frame = self.view.frame;
    }
    return activityViewController.view;
}

- (UIView *)errorView {
    if (!errorViewController) {
        errorViewController = [[NoticeViewController alloc] initWithNibName:@"ErrorView" bundle:nil];
        errorViewController.message = LocalizedString(@"Error!");
        [self.view addSubview:errorViewController.view];
        errorViewController.view.frame = self.view.frame;
    }
    return errorViewController.view;
}




//MARK: -
//MARK: UIViewController

- (void)viewDidLoad {
    [super viewDidLoad];
        
    self.versionPreviousButton = [[[UIBarButtonItem alloc]
                                   initWithBarButtonSystemItem:UIBarButtonSystemItemRewind
                                                        target:self
                                                        action:@selector(versionPrevious)] autorelease];
    
    self.versionNextButton = [[[UIBarButtonItem alloc]
                               initWithBarButtonSystemItem:UIBarButtonSystemItemFastForward
                                                    target:self
                                                    action:@selector(versionNext)] autorelease];    
    
    self.versionLabel = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 170, 33)] autorelease];
    self.versionLabel.backgroundColor = [UIColor clearColor];
    self.versionLabel.textColor = [UIColor whiteColor];
    self.versionLabel.textAlignment = UITextAlignmentCenter;
    self.versionLabel.font = [UIFont boldSystemFontOfSize:13.0];
    
    UIBarButtonItem *labelButton = [[[UIBarButtonItem alloc] initWithCustomView:self.versionLabel]
                                    autorelease];
    
    UIBarButtonItem *flexLeft = [[[UIBarButtonItem alloc]
                                  initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                       target:nil
                                                       action:nil] autorelease];
    
    UIBarButtonItem *flexRight = [[[UIBarButtonItem alloc]
                                   initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                        target:nil
                                                        action:nil] autorelease];
    
    self.toolbarItems = [NSArray arrayWithObjects:
                         self.versionPreviousButton,
                         flexLeft,
                         labelButton,
                         flexRight,
                         self.versionNextButton,
                         nil];    
    
    if (self.file.isStale || self.file.isPartial) {
        if (!loaded)
            self.activityView.hidden = NO;
        [[GSSCommunicator defaultCommunicator] updateMetaOfObject:self.file];
    } else {
        [self reloadMeta];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setToolbarHidden:YES animated:YES];
    [self.file addObserver:self forKeyPath:@"meta" options:0 context:NULL];
    [self.file addObserver:self forKeyPath:@"data" options:0 context:NULL];
    [self.file addObserver:self forKeyPath:@"error" options:0 context:NULL];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.file removeObserver:self forKeyPath:@"meta"];
    [self.file removeObserver:self forKeyPath:@"data"];
    [self.file removeObserver:self forKeyPath:@"error"];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	return YES;
}


//MARK: -
//MARK: UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
	if (buttonIndex == 1) {
        [[GSSCommunicator defaultCommunicator] updateFileObject:self.file];
        self.activityView.hidden = NO;
    }
    
    [alertView release];
}


//MARK: Public Methods

- (void)reloadMeta {
    self.title = self.file.name;
    
    if (self.file.versioned) {
        [self.navigationController setToolbarHidden:NO animated:YES];
        self.versionLabel.text = [NSString stringWithFormat:LocalizedString(@"{Version}"),
                                                            self.file.version];
        if (!latestVersion)
            latestVersion = self.file.version;
        
        self.versionPreviousButton.enabled = self.file.version > 1;
        self.versionNextButton.enabled = self.file.version < latestVersion;
    } else {
        [self.navigationController setToolbarHidden:YES animated:YES];
    }

    [self.file updateMetaAccessDate];

    if (self.file.hasExpiredData) {
        [self downloadData];
    } else {
        [self.file updateDataAccessDate];
        [self reloadData];
        loaded = YES;
    }    
}

- (void)reloadData {
    // To be overriden by subclasses
}


//MARK: -
//MARK: IBActions

- (void)loadVersion:(NSInteger)version {
    [self.file removeObserver:self forKeyPath:@"meta"];
    [self.file removeObserver:self forKeyPath:@"data"];
    [self.file removeObserver:self forKeyPath:@"error"];
    
    if (version != latestVersion) {
        NSString *uri = [self.file uriForVersion:version];
        self.file = [[GSSCommunicator defaultCommunicator] objectWithURI:uri withType:self.file.type];
    } else {
        NSString *uri = [self.file.uri stringByDeletingURIQuery];
        self.file = [[GSSCommunicator defaultCommunicator] objectWithURI:uri withType:self.file.type];
    }

    
    [self.file addObserver:self forKeyPath:@"meta" options:0 context:NULL];
    [self.file addObserver:self forKeyPath:@"data" options:0 context:NULL];
    [self.file addObserver:self forKeyPath:@"error" options:0 context:NULL];
    
    loaded = NO;
    [self reloadMeta];
}

- (void)versionPrevious {
    [self loadVersion:self.file.version - 1];
}

- (void)versionNext {
    [self loadVersion:self.file.version + 1];
}

@end
